package com.jfinal.weixin.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import com.jfinal.weixin.sdk.encrypt.AesException;

/**
 * 
 * @author Reed
 * @Email 
 * 
 */
public class WxJSsign {
	public static String create_timestamp() {
	    return Long.toString(System.currentTimeMillis() / 1000);
	}
	
	public static String create_nonce_str() {
	    return UUID.randomUUID().toString();
	}
	
	public static Map<String,Object> sign(String jsapi_ticket, String url) {
		String signature = "";
		String nonceStr = WxJSsign.create_nonce_str();
        String timeStamp = WxJSsign.create_timestamp();
		// 注意这里参数名必须全部小写，且必须有序
		String string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonceStr
		        + "&timestamp=" + timeStamp + "&url=" + url;

		System.out.println("[string1] = " + string1);
		Map<String,Object> signatureMap = new HashMap<String,Object>();
		try {
		    MessageDigest crypt = MessageDigest.getInstance("SHA-1");
		    crypt.reset();
		    crypt.update(string1.getBytes("UTF-8"));
		    signature = byteToHex(crypt.digest());
		    signatureMap.put("timestamp", timeStamp);
		    signatureMap.put("nonceStr", nonceStr);
		    signatureMap.put("signature", signature);
		    System.out.println("[signature] = " + signature);

		} catch (NoSuchAlgorithmException e) {
		    e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
		    e.printStackTrace();
		}
		return signatureMap;
	}
	
	private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }
	
	
	/**
     * 用SHA1算法生成安全签名
     * 
     * @param token
     *            票据
     * @param timestamp
     *            时间戳
     * @param nonce
     *            随机字符串
     * @param encrypt
     *            密文
     * @return 安全签名
     * @throws NoSuchAlgorithmException
     * @throws AesException
     */
    public String getSHA1(String token, String timestamp, String nonce)
            throws NoSuchAlgorithmException {
        String[] array = new String[] { token, timestamp, nonce };
        StringBuffer sb = new StringBuffer();
        // 字符串排序
        Arrays.sort(array);
        for (int i = 0; i < 3; i++) {
            sb.append(array[i]);
        }
        String str = sb.toString();
        // SHA1签名生成
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.update(str.getBytes());
        byte[] digest = md.digest();

        StringBuffer hexstr = new StringBuffer();
        String shaHex = "";
        for (int i = 0; i < digest.length; i++) {
            shaHex = Integer.toHexString(digest[i] & 0xFF);
            if (shaHex.length() < 2) {
                hexstr.append(0);
            }
            hexstr.append(shaHex);
        }
        return hexstr.toString();
    }

}